package com.ylsf.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.ylsf.blog.mapper.ArticleMapper;
import com.ylsf.blog.mapper.CommentMapper;
import com.ylsf.blog.mapper.UserMapper;
import com.ylsf.blog.pojo.Article;
import com.ylsf.blog.pojo.ArticleComment;
import com.ylsf.blog.pojo.Comment;
import com.ylsf.blog.service.ListService;
import com.ylsf.blog.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章列表服务实现类
 */
public class ListServiceImpl implements ListService {
    @Override
    public Integer computeListPage(String username) {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);
        List<Article> articles = mapper.selectByAuthor(username);
        int count=0;
        if(articles.size()%3==0){
            count=articles.size()/3;
        }else {
            count=articles.size()/3+1;
        }
        SqlSessionUtil.close(sqlSession);
        return count;
    }

    @Override
    public List<ArticleComment> displayUserArticles(String username, Integer startPage) {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        ArticleMapper mapper = sqlSession.getMapper(ArticleMapper.class);
        CommentMapper commentMapper = sqlSession.getMapper(CommentMapper.class);
        //开启分页组件，每页显示三条记录
        PageHelper.startPage(startPage,3);
        //根据姓名查询该用户所有的文章信息
        List<Article> articles = mapper.selectByAuthor(username);
        List<ArticleComment> articleComments=new ArrayList<ArticleComment>();
        for(Article article:articles){
            List<Comment> comments = commentMapper.selectCommentsArticle(article.getId());
            articleComments.add(new ArticleComment(article.getId(),article.getTitle(), article.getContent(),
                    article.getPublishedTime(),
                    article.getAuthor(),comments));
        }
        SqlSessionUtil.close(sqlSession);
        return articleComments;
    }

    @Override
    public List<Comment> displayArticleComments(Integer id,Integer startPage) {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CommentMapper mapper = sqlSession.getMapper(CommentMapper.class);
        PageHelper.startPage(startPage,3);
        List<Comment> comments = mapper.selectCommentsArticle(id);
        SqlSessionUtil.close(sqlSession);
        return comments;
    }
}
